package net.wicp.tams.common.micro.connector;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.executor.IConfigManager;
import net.wicp.tams.common.connector.executor.impl.CommonService;
import net.wicp.tams.common.exception.ExceptAll;
import net.wicp.tams.common.exception.param.Response;
import net.wicp.tams.common.web.J2EEAssist;

/***
 * 默认的处理器
 * 
 * @author zhoujunhui
 *
 */
@Slf4j
public class ConnectorServlet extends HttpServlet {
	private static final long serialVersionUID = -1578783960005731596L;

	@Autowired
	private CommonService commonService;
	@Autowired
	public IConfigManager configmanager;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String requestBody = IOUtil.slurp(req.getInputStream());
		JSONObject params = JSONObject.parseObject(requestBody);
		CusDynaBean inputBean = configmanager.getInputBeanInputBody(params);
		CusDynaBean outbean = commonService.exe(inputBean);
		resp.setCharacterEncoding("UTF-8");
		if (outbean == null) {
			resp.setStatus(ExceptAll.project_other.getHttpCode());
			outbean = configmanager.getConfig(configmanager.getAppkeyByInputBody(params))
					.newOutBean(ExceptAll.project_other);
			outbean.set(Response.errMsg, "返回了空值");
		} else {
			Object httpstatusobj = outbean.get(Response.http);
			log.info("-----------------------------http状态:" + httpstatusobj + "-----------------------");
			int status =  ExceptAll.getHttp(String.valueOf(httpstatusobj));
			resp.setStatus(status);
		}
		J2EEAssist.returnJsonResponse(resp, outbean.getJsonObj().toJSONString());
	}
}
